package com.xz.courseschedule.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xz.courseschedule.entity.*;
import com.xz.courseschedule.mapper.*;
import com.xz.courseschedule.service.ClassesService;
import com.xz.courseschedule.service.RoomService;
import com.xz.courseschedule.service.TaskService;
import com.xz.courseschedule.service.UploadService;
import com.xz.courseschedule.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Objects;

/**
 * @Author: zys
 * @CreateTime: 2025-05-23
 */

@Service
public class UploadServiceImpl implements UploadService {

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private ClassesMapper classesMapper;

    @Resource
    private RoomMapper roomMapper;

    @Resource
    private TeacherMapper teacherMapper;

    @Resource
    private CourseMapper courseMapper;

    @Resource
    private ClassesService classesService;

    @Resource
    private RoomService roomService;

    @Resource
    private TaskService taskService;

    @Override
    public Result uploadTask(MultipartFile file) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<Task> taskList = null;
        try {
            taskList = ExcelImportUtil.importExcel(file.getInputStream(), Task.class, params);//使用excl文件进行导入
        }catch (Exception e){
            System.out.println("导入排课任务失败:"+e.getMessage());
            // todo 这里可以使用log进行日志打印
        }
        assert taskList != null;//进行断言处理，相当于if语句处理，classesList不为空时进行操作
        return saveTask(taskList) ? Result.success("导入排课任务成功") :  Result.error(400,"导入排课任务失败");
    }



    @Override
    public Result uploadClass(MultipartFile file) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<Classes> classesList = null;
        try {
            classesList = ExcelImportUtil.importExcel(file.getInputStream(), Classes.class, params);//使用excl文件进行导入
        }catch (Exception e){
            System.out.println("导入班级失败:"+e.getMessage());
            // todo 这里可以使用log进行日志打印
        }
        assert classesList != null;//进行断言处理，相当于if语句处理，classesList不为空时进行操作
        return saveClass(classesList) ? Result.success("导入班级成功") :  Result.error(400,"导入班级失败");
    }


    @Override
    public Result uploadRoom(MultipartFile file) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<Room> roomList = null;
        try {
            roomList = ExcelImportUtil.importExcel(file.getInputStream(), Room.class,params);
        } catch (Exception e) {
            System.out.println("导入教室失败:"+e.getMessage());
        }
        assert roomList != null;
        return saveRoom(roomList) ? Result.success("导入教室成功") : Result.error(400,"导入教室失败");
    }

    /**
     * 清空旧任务表的数据
     */
    private void clearTaskOld(){
        taskMapper.clearClassTaskOld();;
    }

    private boolean saveTask(List<Task> taskList) {
        clearTaskOld();
        int i = 0;
        System.out.println(taskList);
        //遍历课程任务插入数据库
        for (Task task:taskList){
            Task t = new Task();
            BeanUtils.copyProperties(task,t);
            //进行导入的保存到任务表中的数据库中
            boolean b = taskService.save(t);

            //新建老师类，准备从任务表中的老师导入到对应的老师表数据库中
            Teacher teacher = new Teacher();
            teacher.setTeacherNo(t.getTeacherNo());//设置老师编号
            teacher.setTeacherName(t.getTeacherName());//设置老师名字

            //新建课程表
            Course course = new Course();
            course.setCourseNo(t.getCourseNo());//设置课程编号
            course.setCourseName(t.getCourseName());//设置课程名称
            course.setCourseAttr(t.getCourseAttr());//设置课程属性

            //通过计数查询该教师是否存在教师表里面，如果存在则不进行添加，反之不存在则进行添加
            Long count1 = teacherMapper.selectCount(new LambdaQueryWrapper<Teacher>()
                    .eq(Teacher::getTeacherNo, teacher.getTeacherNo())
            );
            if (count1==0)
                teacherMapper.insert(teacher);
            //通过技术查询该课程是否存在课程表里面，如果存在则不进行添加，反之不存在则进行添加
            Long count2 = courseMapper.selectCount(new LambdaQueryWrapper<Course>()
                    .eq(Course::getCourseNo, course.getCourseNo()));
            if (count2==0)
                courseMapper.insert(course);
            //判断b是否成功,如果成功则对计数器i进行加1处理
            if (b)
                i+=1;
        }
        return i == taskList.size();
    }
    private boolean saveRoom(List<Room> roomList) {
        int i = 0;
        int a = 0;
        //遍历教室任务插入数据库
        for (Room room:roomList){
            Room r = new Room();
            List<Room> selectRoomNo = roomMapper.selectRoomNo();//查询教室编号
            for (int j = 0;j<selectRoomNo.size();j++){
                //判断Excl表的教室编号是否鱼数据库一致的
                if (Objects.equals(selectRoomNo.get(j).getRoomNo(),room.getRoomNo())){
                    a+=1;
                }
            }
            if (a!=0){
                break;
            }
            BeanUtils.copyProperties(room,r);
            boolean b = roomService.save(r);
            if (b)
                i+=1;
        }
        return i == roomList.size();
    }


    private boolean saveClass(List<Classes> classesList) {
        int i = 0;
        int a = 0;
        //遍历班级任务插入数据库
        for (Classes classes:classesList){
            Classes c = new Classes();
            List<Classes> selectClassesNo = classesMapper.selectClassNo();//查询班级编号
            for (int j = 0;j<selectClassesNo.size();j++){
                //判断Excl表的教室编号是否鱼数据库一致的
                if (Objects.equals(selectClassesNo.get(j).getClassNo(),classes.getClassNo())){
                    a+=1;
                }
            }
            if (a!=0){
                break;
            }
            BeanUtils.copyProperties(classes,c);
            boolean b = classesService.save(c);
            if (b)
                i+=1;
        }
        return i == classesList.size(); // 只要有成功导入的就返回true
    }

}
